<template>
  <a-spin :spinning="confirmLoading">
    <ants-form-container :disabled="formDisabled">
      <a-form slot="detail" :form="form">
        <a-row>
          <a-col :span="24">
            <a-form-item label="头像" :label-col="labelCol" :wrapper-col="wrapperCol">
              <ants-image-upload biz-path="ants-avatar" v-decorator="['avatar', validatorRules.avatar]" is-multiple/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="用户姓名" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input v-decorator="['realname', validatorRules.realname]" placeholder="请输入姓名"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="用户账号" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input
                v-decorator.trim="['username', validatorRules.username]"
                placeholder="请输入用户名"
                :read-only="!!model.id"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="登陆密码" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input v-decorator="['password', validatorRules.password]" type="password" placeholder="请输入登陆密码"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="确认密码" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input
                v-decorator="['confirmPassword', validatorRules.confirmPassword]"
                type="password"
                placeholder="请确认密码"
                @blur="handleConfirmBlur"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="生日" :label-col="labelCol" :wrapper-col="wrapperCol">
              <ants-date v-decorator="['birthday']" placeholder="请选择生日" :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="性别" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-select
                v-decorator="['sex']"
                placeholder="请选择性别"
              >
                <a-select-option value="1">
                  男
                </a-select-option>
                <a-select-option value="2">
                  女
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="电话" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input v-decorator="['phone', validatorRules.phone]" placeholder="请输入手机号码"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="邮箱" :label-col="labelCol" :wrapper-col="wrapperCol">
              <!--              <a-input v-decorator="['email', validatorRules.email]" placeholder="请输入邮箱" />-->
              <a-auto-complete
                placeholder="请输入邮箱"
                @search="handleSearch"
                v-decorator="['email', validatorRules.email]"
              >
                <template slot="dataSource">
                  <a-select-option v-for="item in emailResult" :key="item">
                    {{ item }}
                  </a-select-option>
                </template>
              </a-auto-complete>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="验证码" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-col :span="14">
                <a-input v-decorator="['captcha', validatorRules.captcha]" placeholder="根据邮箱获取验证码"/>
              </a-col>
              <a-col :span="10" style="text-align: right">
                <a-button type="link" @click="getCaptcha" v-if="captchaShow">
                  获取验证码
                </a-button>
                <a-button type="link" v-else>
                  {{ count }} 秒后重试
                </a-button>
              </a-col>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </ants-form-container>
  </a-spin>
</template>

<script>
import AntsFormContainer from '@/components/ants/AntsFormContainer'
import pick from 'lodash.pick'
import AntsImageUpload from '@/components/ants/AntsImageUpload'
import AntsDate from '@/components/ants/AntsDate'
import store from '@/store'
import { duplicateCheck, sendCaptcha } from '@/api/api'

export default {
  name: 'ArticleRegisterForm',
  components: {
    AntsFormContainer,
    AntsImageUpload,
    AntsDate
  },
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      form: this.$form.createForm(this),
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      validatorRules: {
        username: {
          rules: [{
            required: true, message: '请输入用户账号!'
          }, {
            validator: this.validateUsername
          }]
        },
        avatar: {
          rules: [{
            required: true, message: '请上传头像!'
          }]
        },
        password: {
          rules: [{
            required: true,
            pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/,
            message: '密码最少8位字符，由 数字、大小写字母 和 特殊符号 组成！'
          }, {
            validator: this.validateToNextPassword
          }]
        },
        confirmPassword: {
          rules: [{
            required: true, message: '请重新输入登陆密码!'
          }, {
            validator: this.compareToFirstPassword
          }]
        },
        realname: { rules: [{ required: true, message: '请输入用户名称!' }] },
        captcha: { rules: [{ required: true, message: '请输入验证码!' }] },
        phone: { rules: [{ validator: this.validatePhone }] },
        email: {
          rules: [{ required: true, message: '请输入邮箱!' },
            { validator: this.validateEmail }]
        }
      },
      url: {
        register: '/sys/register'
      },
      confirmLoading: false,
      confirmDirty: false,
      userId: '',
      emailResult: [],
      captchaShow: true,
      count: '',
      timer: null
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    }
  },
  methods: {
    handleSearch(value) {
      let result
      if (!value || value.indexOf('@') >= 0) {
        result = []
      } else {
        result = [
          'gmail.com',
          'yahoo.com',
          'msn.com',
          'hotmail.com',
          'aol.com',
          'ask.com',
          'live.com',
          'qq.com',
          '0355.net',
          '163.com',
          '163.net',
          '263.net',
          '3721.net',
          'yeah.net',
          'googlemail.com',
          'mail.com'
        ].map(domain => `${value}@${domain}`)
      }
      this.emailResult = result
    },
    handleConfirmBlur(e) {
      const value = e.target.value
      this.confirmDirty = this.confirmDirty || !!value
    },
    add() {
      this.edit({})
    },
    edit(record) {
      this.form.resetFields()
      this.userId = record.id
      this.model = Object.assign({}, record)
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'realname', 'username', 'birthday', 'sex', 'email', 'phone', 'avatar'))
      })
    },
    validateToNextPassword(rule, value, callback) {
      const form = this.form
      const confirmpassword = form.getFieldValue('confirmpassword')

      if (value && confirmpassword && value !== confirmpassword) {
        callback('两次输入的密码不一样！')
      }
      if (value && this.confirmDirty) {
        form.validateFields(['confirm'], { force: true })
      }
      callback()
    },
    compareToFirstPassword(rule, value, callback) {
      const form = this.form
      if (value && value !== form.getFieldValue('password')) {
        callback('两次输入的密码不一样！')
      } else {
        callback()
      }
    },
    validatePhone(rule, value, callback) {
      if (!value) {
        callback()
      } else {
        // update-begin--Author:kangxiaolin  Date:20190826 for：[05] 手机号不支持199号码段--------------------
        if (new RegExp(/^1[3|4|5|7|8|9][0-9]\d{8}$/).test(value)) {
          // update-end--Author:kangxiaolin  Date:20190826 for：[05] 手机号不支持199号码段--------------------

          var params = {
            tableName: 'sys_user',
            fieldName: 'phone',
            fieldVal: value,
            dataId: this.userId
          }
          duplicateCheck(params).then((res) => {
            if (res.success) {
              callback()
            } else {
              callback('手机号已存在!')
            }
          })
        } else {
          callback('请输入正确格式的手机号码!')
        }
      }
    },
    validateEmail(rule, value, callback) {
      if (!value) {
        callback()
      } else {
        if (new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(value)) {
          var params = {
            tableName: 'sys_user',
            fieldName: 'email',
            fieldVal: value,
            dataId: this.userId
          }
          duplicateCheck(params).then((res) => {
            if (res.success) {
              callback()
            } else {
              callback('邮箱已存在!')
            }
          })
        } else {
          callback('请输入正确格式的邮箱!')
        }
      }
    },
    validateUsername(rule, value, callback) {
      var params = {
        tableName: 'sys_user',
        fieldName: 'username',
        fieldVal: value,
        dataId: this.userId
      }
      duplicateCheck(params).then((res) => {
        if (res.success) {
          callback()
        } else {
          callback('用户名已存在!')
        }
      })
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          const formData = Object.assign(this.model, values)

          store.dispatch('user/addOrUpdateUser', {
            url: that.url.register,
            method: 'post',
            params: formData
          }).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }
      })
    },
    getCaptcha() {
      if (this.form.fieldsStore.fields.email) {
        const value = this.form.fieldsStore.fields.email.value
        if (new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(value)) {

          const params = {
            email: value
          }
          sendCaptcha(params).then((res) => {
            if (res.success) {
              const TIME_COUNT = 60
              if (!this.timer) {
                this.count = TIME_COUNT
                this.captchaShow = false
                this.timer = setInterval(() => {
                  if (this.count > 0 && this.count <= TIME_COUNT) {
                    this.count--
                  } else {
                    this.captchaShow = true
                    clearInterval(this.timer)
                    this.timer = null
                  }
                }, 1000)
              }
            }
          })
        } else {
          this.$message.error('请输入正确邮箱！')
        }
      } else {
        this.$message.error('请输入邮箱！')
      }
    }
  }
}
</script>

<style scoped>

</style>
